<?php

/**
 * 73YC 商品详情
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

if ($_REQUEST['id']=='1658') {
    header("location: glair.php?isInfo=1");
}

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}
assign_template();
$goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;
/*------------------------------------------------------ */
//-- 商品购买记录ajax处理
/*------------------------------------------------------ */
if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'gotopage')
{

    include('includes/cls_json.php');
    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '');
    $goods_id   = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    $page    = (isset($_REQUEST['page'])) ? intval($_REQUEST['page']) : 1;

    if (!empty($goods_id))
    {
        $bns = assign_bought_notes($goods_id,0,$page);
        $smarty->assign('notes', $bns['bought_notes']);
        $smarty->assign('pager', $bns['pager']);
        $res['result'] = $GLOBALS['smarty']->fetch('library/bought_notes.lbi');
    }
    die($json->encode($res));
}


/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

$cache_id = $goods_id . '-' . $_SESSION['user_rank'].'-'.$_CFG['lang'];
$cache_id = sprintf('%X', crc32($cache_id));

// if (!$smarty->is_cached('goods.dwt', $cache_id))
// {
    /* 获得商品的信息 */
    $goods = get_goods_info($goods_id);
    if ($goods === false || !$goods['is_on_sale'] )
    {
        /* 如果没有找到任何记录则跳回到首页 */
        ecs_header("Location: /errpage/goods.php\n");
        exit;
    }
    else
    {
        /* 找出关联产品 */
        $id = $goods_id;
        if($id){
            $sql = 'SELECT link_goods_id FROM ' . $GLOBALS['ecs']->table('link_goods') . " AS lg " . 
                    " WHERE lg.goods_id = $id ";
            $link_goods = $GLOBALS['db']->getAll($sql);
            foreach ($link_goods as $key => $value) {
                $link_goods_id[] = $value['link_goods_id'];
            }
            if($link_goods_id){
                $id_str = "$id, " . implode(',', $link_goods_id);
            }else{
                $id_str = "$id";
            }
        }

        /* 统计其和其关联产品总销量 */
        $sql = ' SELECT SUM(goods_number) ' .
               ' FROM ' . $GLOBALS['ecs']->table('order_goods') . " WHERE goods_id IN ($id_str)" ;
        $sales_count = $GLOBALS['db']->getOne($sql);
        $goods['comment_rank'] = $goods['comment_rank']*20;//商品评分
        /*关联商品*/
        $linked_goods = get_linked_goods($goods_id);
        // 分享到微博链接
        $goods['share_url'] = "http://service.weibo.com/share/share.php?url=".urlencode("http://www.eggms.com/goods.php?id=".$goods['goods_id'])."&type=button&ralateUid=2809270770&language=zh_cn&title=".urlencode($goods['goods_name'])."&pic=".urlencode('http://www.eggms.com/'.$goods['goods_img'])."&searchPic=false&style=simple";
        $smarty->assign('goods_id',           $goods['goods_id']);
        $smarty->assign('promote_end_time',   $goods['gmt_end_time']);
        /* meta */
        $smarty->assign('keywords',           htmlspecialchars($goods['keywords']));
        $smarty->assign('description',        htmlspecialchars($goods['goods_brief']));
        /* 获取标题与当前位置 */
        $position = assign_ur_here($goods['cat_id'], $goods['goods_name']);
        $smarty->assign('page_title',          $position['title']);                    // 页面标题
        $properties = get_goods_properties($goods_id);  // 获得商品的规格和属性
 
        //商品促销中处理
        if($goods['promote_end_date']>time()&&$goods['promote_start_date']<time()){
            $goods['goods_number'] = limit_num($goods_id);//重置库存
            dump(limit_num($goods_id));
            $smarty->assign('end_time',        ($goods['promote_end_date']-time())); 
            $smarty->assign('end_time_now',    promote_time_out($goods['promote_end_date']-time()));
        }
        // 评论总数
        $cmt = assign_comment($goods['goods_id'],0);
        $smarty->assign('comments',     $cmt['comments']);
        $smarty->assign('pager',        $cmt['pager']);
        /* 购买记录总数 */
        $bns = assign_bought_notes($goods['goods_id'],0);
        $smarty->assign('count',        $bns['pager']['record_count']);
        /*已选商品信息*/
        if($_POST['buy_goods_html']){
            foreach(explode('/',$_POST['buy_goods_html']) AS $key => $value){
                foreach (explode('-',rtrim($value,"-")) as $k => $v) {
                    $buy_goods[$k][$key] = $v;
                }
            }
        }
        $smarty->assign('pictures',            get_goods_gallery($goods_id));                    // 商品相册
        $smarty->assign('buy_goods',           $buy_goods);                                      // 商品已选购
        $goods['goods_desc'] = str_replace(array("\r\n", "\r", "\n"), "", $goods['goods_desc']);
        $smarty->assign('goods',               $goods);                                          // 商品信息
        $smarty->assign('specification',       $properties['spe']);                              // 商品规格
        $smarty->assign('related_goods',       $linked_goods);                                   // 关联商品
        $smarty->assign('is_buy',              is_buy());
        $smarty->assign('Sales',  $sales_count);//销量
        $smarty->assign('id',           $goods_id);//商品ID
        $smarty->assign('volume_price_list',$volume_price_list);    // 商品优惠价格区间
    }
// }


/* 记录浏览历史 */
if (!empty($_COOKIE['ECS']['history']))
{
    $history = explode(',', $_COOKIE['ECS']['history']);
    array_unshift($history, $goods_id);
    $history = array_unique($history);

    while (count($history) > $_CFG['history_number'])
    {
        array_pop($history);
    }

    setcookie('ECS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30);
}
else
{
    setcookie('ECS[history]', $goods_id, gmtime() + 3600 * 24 * 30);
}


/* 更新点击次数 */
$db->query('UPDATE ' . $ecs->table('goods') . " SET click_count = click_count + 1 WHERE goods_id = '$goods[goods_id]'");
// 更新看过记录
if($_SESSION['user_id'] && $goods['goods_id']){
    lookat($goods['goods_id'],$_SESSION['user_id']);
}
$smarty->assign('now_time',  gmtime());           // 当前系统时间
if (empty($goods['goods_desc']) && !empty($goods['get_url'])) {
    header("location: {$goods['get_url']}");
    exit;
}

// var_dump($_SESSION);
if (!empty($goods['is_taodan'])) {
    /* 获取相关分类 */
    $sql = "SELECT parent_id FROM {$ecs->table('category')} WHERE cat_id = '{$goods['cat_id']}'";
    $catParentId = $db->getOne($sql);
    $sql = "SELECT cat_id, cat_name FROM {$ecs->table('category')} WHERE parent_id = '{$catParentId}'";
    $catList = $db->getAll($sql);
    $smarty->assign('catList', $catList);
    $smarty->display('goods_taodan.dwt');
} else {
    
    //去拿用户信息
    $user_array = array();
    $sql = 'SELECT * FROM ' . $ecs->table('users') . ' WHERE user_id = '.$_SESSION['user_id'];
    $user_array = $db->getRow($sql);
    
    $smarty->assign('user_array', $user_array);

//     var_dump($goods);
    $smarty->display('goods.dwt');
}


/**
 * 获得指定商品的关联商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{

    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_thumb, g.goods_img, g.goods_brief, g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('link_goods') . ' AS lg ' . 
                "ON g.goods_id = lg.link_goods_id OR g.goods_id = lg.goods_id " . 
            "WHERE lg.goods_id = '$goods_id' AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.is_on_sale = 1 ORDER BY g.sort_order,g.goods_id ASC";

    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']     = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']   = $row['goods_name'];
        $arr[$row['goods_id']]['goods_brief']  = end(explode('-',$row['goods_name']));
        $arr[$row['goods_id']]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
            sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$row['goods_id']]['goods_thumb']  = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        if($row['market_price'] > 0){//当存在市场价时的市场价
            $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']);
        }else{//当不存在市场价时的市场价
            $arr[$row['goods_id']]['market_price'] = price_format(sprintf('%.1f',($row['shop_price'])*1.2));
        }
        $arr[$row['goods_id']]['shop_price']   = price_format($row['shop_price']);
        $arr[$row['goods_id']]['url']          = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0)
        {
            $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
        }
        else
        {
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }

    return $arr;
}

